<template>
  <view class="settings-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <image src="/static/account/back.png" mode="widthFix"></image>
      </view>
      <text class="title">账号设置</text>
    </view>

    <!-- 用户信息卡片 -->
    <view class="user-info-card">
      <view class="avatar-container" @click="openAvatarSetting">
        <image :src="userInfo.avatar" class="avatar"></image>
        <view class="edit-avatar">
          <image src="/static/account/edit.png" mode="widthFix"></image>
        </view>
      </view>
      <view class="username-container" @click="openUsernameSetting">
        <text class="username">{{ userInfo.username }}</text>
        <image src="/static/account/back.png" mode="widthFix" class="arrow"></image>
      </view>
    </view>

    <!-- 设置项列表 -->
    <view class="settings-list">
      <!-- 安全设置 -->
      <view class="section-title">安全设置</view>
      <view class="setting-item" @click="openPasswordSetting">
        <image src="/static/account/password.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">密码修改</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>
      <view class="setting-item" @click="openPhoneSetting">
        <image src="/static/account/phone.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">绑定手机号</text>
        <text class="item-value">{{ userInfo.phone || '未绑定' }}</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>
      <view class="setting-item" @click="openEmailSetting">
        <image src="/static/account/email.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">绑定邮箱</text>
        <text class="item-value">{{ userInfo.email || '未绑定' }}</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>

      <!-- 账号绑定 -->
      <view class="section-title">账号绑定</view>
      <view class="setting-item" @click="bindWechat">
        <image src="/static/account/wechat.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">微信绑定</text>
        <text class="item-value" :class="{'bound': userInfo.wechatBound}">{{ userInfo.wechatBound ? '已绑定' : '未绑定' }}</text>
        <image src="/static/icons/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>
      <view class="setting-item" @click="bindQQ">
        <image src="/static/account/QQ.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">QQ绑定</text>
        <text class="item-value" :class="{'bound': userInfo.qqBound}">{{ userInfo.qqBound ? '已绑定' : '未绑定' }}</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>

      <!-- 其他设置 -->
      <view class="section-title">其他设置</view>
      <view class="setting-item" @click="openNotificationSetting">
        <image src="/static/account/notification.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">消息通知</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>
      <view class="setting-item" @click="clearCache">
        <image src="/static/account/cache.png" mode="widthFix" class="item-icon"></image>
        <text class="item-text">清除缓存</text>
        <text class="item-value">{{ cacheSize }}</text>
        <image src="/static/account/arrow-right.png" mode="widthFix" class="arrow"></image>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="logout-container">
      <button type="default" class="logout-btn" @click="confirmLogout">退出登录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        avatar: '/static/default_avatar.png',
        username: '用户12345',
        phone: '138****1234',
        email: 'example@mail.com',
        wechatBound: true,
        qqBound: false
      },
      cacheSize: '23.5MB'
    }
  },
  onLoad() {
    // 加载本地存储的用户信息
    const storedUser = uni.getStorageSync('userInfo');
    if (storedUser) {
      this.userInfo = storedUser;
    }
    // 加载本地存储的缓存大小
    const storedCache = uni.getStorageSync('cacheSize');
    if (storedCache) {
      this.cacheSize = storedCache;
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 持久化保存用户信息到本地存储
    saveUserInfo() {
      uni.setStorageSync('userInfo', this.userInfo);
    },

    // 封装图片上传函数（需后端接口支持，替换实际URL）
    uploadImage(tempFilePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'https://your-api-domain.com/upload-avatar', // 替换为实际后端接口
          filePath: tempFilePath,
          name: 'avatar', // 与后端约定的字段名
          header: {
            // 若需鉴权，添加Token（示例）：
            // 'Authorization': `Bearer ${uni.getStorageSync('token')}`
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              if (data.code === 200) { // 假设后端返回code=200为成功
                resolve(data.data.avatarUrl); // 后端返回的永久URL
              } else {
                reject(`后端错误：${data.msg}`);
              }
            } catch (parseErr) {
              reject(`响应解析失败：${parseErr.message}`);
            }
          },
          fail: (err) => {
            reject(`上传失败：${err.errMsg}`);
          }
        });
      });
    },

    // 打开头像设置（支持拍照+上传+持久化）
    openAvatarSetting() {
      uni.showActionSheet({
        itemList: ['从相册选择', '拍照'],
        success: async (res) => { // 异步处理上传
          const sourceType = res.tapIndex === 0 ? ['album'] : ['camera'];
          uni.chooseImage({
            count: 1,
            sourceType,
            success: async (imgRes) => { // 嵌套异步
              try {
                // 1. 上传图片到服务器，获取永久URL
                const avatarUrl = await this.uploadImage(imgRes.tempFilePaths[0]);
                // 2. 更新用户信息（永久URL）
                this.userInfo.avatar = avatarUrl; 
                this.saveUserInfo(); // 持久化到本地
                uni.showToast({ title: '头像更新成功', icon: 'success' });
              } catch (err) {
                console.error('头像更新失败：', err);
                uni.showToast({ 
                  title: err.message || '头像更新失败，请重试', 
                  icon: 'none' 
                });
              }
            },
            fail: (err) => {
              console.error('选择图片失败：', err);
              uni.showToast({ title: '选择图片失败', icon: 'none' });
            }
          });
        },
        fail: (err) => {
          console.error('操作菜单失败：', err);
          uni.showToast({ title: '取消操作', icon: 'none' });
        }
      });
    },

    // 打开用户名设置（支持持久化）
    openUsernameSetting() {
      uni.showModal({
        title: '修改用户名',
        editable: true,
        placeholderText: this.userInfo.username,
        success: (res) => {
          if (res.confirm && res.content.trim()) {
            this.userInfo.username = res.content.trim();
            this.saveUserInfo(); // 保存到本地
            uni.showToast({ title: '用户名修改成功', icon: 'success' });
          }
        }
      });
    },

    // 打开密码设置
    openPasswordSetting() {
      uni.navigateTo({
        url: '/pages/settings/password'
      });
    },

    // 打开手机设置
    openPhoneSetting() {
      if (this.userInfo.phone) {
        uni.navigateTo({ url: '/pages/settings/phone' });
      } else {
        uni.navigateTo({ url: '/pages/settings/phoneBind' });
      }
    },

    // 打开邮箱设置
    openEmailSetting() {
      if (this.userInfo.email) {
        uni.navigateTo({ url: '/pages/settings/email' });
      } else {
        uni.navigateTo({ url: '/pages/settings/emailBind' });
      }
    },

    // 微信绑定（原逻辑不变，如需持久化可扩展）
    bindWechat() {
      if (this.userInfo.wechatBound) {
        uni.showModal({
          title: '确认解绑',
          content: '确定要解除微信绑定吗？',
          success: (res) => {
            if (res.confirm) {
              this.userInfo.wechatBound = false;
              this.saveUserInfo(); // 新增持久化
              uni.showToast({ title: '已解除微信绑定', icon: 'success' });
            }
          }
        });
      } else {
        uni.showToast({ title: '微信绑定功能开发中', icon: 'none' });
      }
    },

    // QQ绑定（新增完整逻辑，支持持久化）
    bindQQ() {
      if (this.userInfo.qqBound) {
        // 已绑定 → 解绑
        uni.showModal({
          title: '确认解绑',
          content: '确定要解除QQ绑定吗？',
          success: (res) => {
            if (res.confirm) {
              this.userInfo.qqBound = false;
              this.saveUserInfo(); // 保存到本地
              uni.showToast({ title: '已解除QQ绑定', icon: 'success' });
            }
          }
        });
      } else {
        // 未绑定 → 模拟绑定（实际需对接后端）
        uni.showModal({
          title: 'QQ绑定',
          content: '请确认QQ授权（模拟流程）',
          success: (res) => {
            if (res.confirm) {
              this.userInfo.qqBound = true;
              this.saveUserInfo(); // 保存到本地
              uni.showToast({ title: 'QQ绑定成功', icon: 'success' });
            }
          }
        });
      }
    },

    // 打开通知设置
    openNotificationSetting() {
      uni.navigateTo({
        url: '/pages/settings/notification'
      });
    },

    // 清除缓存（支持持久化）
    clearCache() {
      uni.showModal({
        title: '清除缓存',
        content: '确定要清除应用缓存吗？',
        success: (res) => {
          if (res.confirm) {
            // 模拟清除（实际需调用 uni.clearStorage 等API）
            this.cacheSize = '0KB';
            uni.setStorageSync('cacheSize', this.cacheSize); // 保存到本地
            uni.showToast({ title: '缓存已清除', icon: 'success' });
          }
        }
      });
    },

    // 确认退出登录
    confirmLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出当前账号吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('token');
            uni.reLaunch({ url: '/pages/login/login' });
          }
        }
      });
    }
  }
}
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary-color: #42b983;
  --text-color: #333;
  --text-light-color: #666;
  --text-hint-color: #999;
  --border-color: #eee;
  --bg-color: #f5f5f5;
  --card-bg: #fff;
  --logout-color: #f56c6c;
}

/* 容器样式 */
.settings-container {
  background-color: var(--bg-color);
  min-height: 100vh;
}

/* 头部样式 */
.header {
  height: 100rpx;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.back-btn image {
  width: 24rpx;
  height: 40rpx;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  width: 100%;
}

/* 用户信息卡片 */
.user-info-card {
  background-color: var(--card-bg);
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar-container {
  position: relative;
  margin-bottom: 30rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 2rpx solid #eee;
}

.edit-avatar {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 48rpx;
  height: 48rpx;
  background-color: var(--primary-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-avatar image {
  width: 24rpx;
  height: 24rpx;
}

.username-container {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: center;
}

.username {
  font-size: 32rpx;
  color: var(--text-color);
  margin-right: 20rpx;
}

.arrow {
  width: 20rpx;
  height: 34rpx;
}

/* 设置项列表 */
.settings-list {
  background-color: var(--card-bg);
  margin-bottom: 30rpx;
}

.section-title {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: var(--text-hint-color);
  background-color: var(--bg-color);
}

.setting-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid var(--border-color);
  position: relative;
}

.setting-item:last-child {
  border-bottom: none;
}

.item-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.item-text {
  font-size: 32rpx;
  color: var(--text-color);
  flex: 1;
}

.item-value {
  font-size: 28rpx;
  color: var(--text-light-color);
  margin-right: 20rpx;
}

.bound {
  color: var(--primary-color);
}

/* 底部按钮 */
.logout-container {
  padding: 30rpx;
}

.logout-btn {
  height: 90rpx;
  background-color: var(--logout-color);
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
}
</style>